/**
 * 
 */
package com.audi.box.server;

import android.content.Context;
import android.util.Log;

import com.audi.box.server.handler.*;
import com.audi.box.server.message.ActionMessage;
import com.audi.box.server.message.AudiMessage;
import com.audi.box.server.message.HandlerException;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * @author HuyPVA
 * 
 */
public class MessageHandler {
	private Context context;
	private HandlerFactory handlerFactory;
	private Gson gson;

	/**
	 * @throws Exception
	 * 
	 */
	public MessageHandler(Context context) {
		if (context != null) {
			this.context = context;
			init();
		} else {
			handlerFactory = HandlerFactory.getInstance();
			gson = new Gson();

		}
	}

	/**
	 * Initialize
	 */
	private void init() {
		handlerFactory = HandlerFactory.create(context);
		gson = new Gson();
	}

	public String processMessage(String msg) {
		Log.d("AudiBox", "[MessageHandler.java] Process msg:" + msg);
		try {
			AudiMessage aMsg = gson.fromJson(msg, AudiMessage.class);
			int actionId = aMsg.getActionID();
			String data = aMsg.getData();
			Handler handler = handlerFactory.getHandler(actionId);
			Object result = handler.process(actionId, data);
			return convertToMsg(actionId, result);
		}  catch (HandlerException he) {
			Log.e("AudiBox",
					"[MessageHandler.java] Hanle msg error" + he.getMessage());
			// return "Server return: " + msg;
			return convertToMsg(ActionMessage.ERROR_HANDLER, he.getMessage());
		} catch (Exception e) {
			Log.e("AudiBox",
					"[MessageHandler.java] Process msg error" + e.getMessage());
			return convertToMsg(ActionMessage.ERROR_HANDLER,
					"Can't convert msg to AudiMessage, msg = " + msg);
		}
	}

	public String convertToMsg(int actionId, Object data) {
		String strData = gson.toJson(data);
		AudiMessage msg = new AudiMessage(actionId, strData);

		String msgJson = gson.toJson(msg);
		Log.d("AudiBox", "[MessageHandler.java] Send msg:" + msgJson);
		return msgJson;
	}
}
